package com.inxedu.os.edu.service.main.impl;

import com.inxedu.os.edu.dao.SysRoleMapper;
import com.inxedu.os.edu.dao.SysUserMapper;
import com.inxedu.os.edu.pojo.SecurityUser;
import com.inxedu.os.edu.pojo.SysUser;
import com.inxedu.os.edu.pojo.SysUserExample;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if(StringUtils.isEmpty(s)){
            throw new UsernameNotFoundException("账号不能为空");
        }
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andLoginNameEqualTo(s);
        List<SysUser> sysUsers = sysUserMapper.selectByExample(example);
        if(sysUsers.isEmpty()){
            throw new UsernameNotFoundException("账号不存在");
        }
        ArrayList<String> arrayList = sysRoleMapper.selectAll();
        List<GrantedAuthority> authorities=new ArrayList<>();
        for (String ss :arrayList){
            if(ss.equals("系统管理员")){
                GrantedAuthority grantedAuthority=new SimpleGrantedAuthority("ROLE_ADMIN");
                authorities.add(grantedAuthority);
            }
            if(ss.equals("老师")){
                GrantedAuthority grantedAuthority=new SimpleGrantedAuthority("ROLE_TEACHER");
                authorities.add(grantedAuthority);
            }
            if(ss.equals("普通管理员")){
                GrantedAuthority grantedAuthority=new SimpleGrantedAuthority("ROLE_GENERAL ADMINISTRATOR");
                authorities.add(grantedAuthority);
            }
            if(ss.equals("销售")){
                GrantedAuthority grantedAuthority=new SimpleGrantedAuthority("ROLE_SALE");
                authorities.add(grantedAuthority);
            }

        }

        SecurityUser securityUser=new SecurityUser(sysUsers.get(0).getLoginName(),sysUsers.get(0).getLoginPwd(),authorities);
        return securityUser;
    }

}
